/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.dao.QuestionTradeDao;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.QuestionTrade;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Dao - 易问易答流水
 */
@Repository("questionTradeDaoImpl")
public class QuestionTradeDaoImpl extends BaseDaoImpl<QuestionTrade, Long> implements QuestionTradeDao {

    @Override
    public QuestionTrade findBySn(String sn) {
        if (sn == null) {
            return null;
        }
        String jpql = "select questionTrades from QuestionTrade questionTrades where lower(questionTrades.sn) = lower(:sn)";
        try {
            return entityManager.createQuery(jpql, QuestionTrade.class).setFlushMode(FlushModeType.COMMIT).setParameter("sn", sn).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     * 判断用户是否购买
     * @param member
     * @param questionId
     * @param paymentStatus
     * @return
     */
    @Override
    public boolean isPay(Member member, Long questionId, QuestionTrade.PaymentStatus paymentStatus) {
        Pageable pageable = new Pageable();
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<QuestionTrade> criteriaQuery = criteriaBuilder.createQuery(QuestionTrade.class);
        Root<QuestionTrade> root = criteriaQuery.from(QuestionTrade.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        if (member != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("buyer"), member));
        }
        if (questionId != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("questionId"), questionId));
        }
        if (paymentStatus != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), paymentStatus));
        }
        criteriaQuery.where(restrictions);
        Page<QuestionTrade> page = super.findPage(criteriaQuery, pageable);
        if(page.getContent().size() > 0) {
            return true;
        }
        return false;
    }
}
